package com.order.service.impl;

import com.order.dto.OrderPageQueryDTO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.order.context.BaseContext;
import com.order.entity.OrderDetail;
import com.order.entity.OrderHistory;
import com.order.entity.ShoppingCart;
import com.order.entity.User;
import com.order.mapper.CartMapper;
import com.order.mapper.OrderDetailMapper;
import com.order.mapper.OrderMapper;
import com.order.result.PageResult;
import com.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private CartMapper cartMapper;


    @Override
    public List<OrderHistory> getOrderHistory() {
        return orderMapper.getByUserId(BaseContext.getCurrentId());
    }

    @Override
    public List<OrderDetail> getOrderDetail(Long orderId) {
        return orderDetailMapper.getByOrderId(orderId);
    }

    /**
     * 订单搜索
     *
     * @param orderPageQueryDTO
     * @return
     */
    public PageResult conditionSearch(OrderPageQueryDTO orderPageQueryDTO) {
        PageHelper.startPage(orderPageQueryDTO.getPage(), orderPageQueryDTO.getPageSize());
        Page<OrderHistory> page =orderMapper.pageQuery(orderPageQueryDTO);

        long total = page.getTotal();
        List<OrderHistory> records = page.getResult();
        return new PageResult(total,records);
    }

    @Override
    public void submit() {
        List<ShoppingCart> carts = cartMapper.getByUserId(BaseContext.getCurrentId());
        BigDecimal total = new BigDecimal(0);
        for (ShoppingCart cart : carts) {
            total = total.add(cart.getAmount());
        }
        OrderHistory orderHistory = OrderHistory.builder()
                .userId(BaseContext.getCurrentId())
                .totalAmount(total)
                .createdTime(LocalDateTime.now())
                .orderData("1")
                .build();
        orderMapper.insert(orderHistory);
        for (ShoppingCart cart : carts) {
            total = total.add(cart.getAmount());
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);

            orderDetail.setOrderId(orderHistory.getId());
            orderDetailMapper.insert(orderDetail);
        }
        cartMapper.deleteByUserId(BaseContext.getCurrentId());
    }
}
